#region license
/*
 * Copyright (C) 2007 CchenSoft.com
 * 
 * See http://www.cchensoft.com/opensource/cc-portal/license.txt
 * 
 * Author: Billy Zhang
 * Email: billy_zh@126.com
 */
#endregion

using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using System.Net;
using System.IO;
using System.Web.UI.WebControls;

using CchenSoft.Framework.Utils;
using CchenSoft.Framework.Attributes;

using CchenSoft.Portal.Model;
using CchenSoft.Portal.Service;

namespace CchenSoft.Portal.Web.Controls
{
    [ParseChildren(true)]
    public class LayoutControl : ChildControl
    {
        [Bean]
        protected IPortalService portalService;

        protected override void InitializeSkin(Control control)
        {
            string hostName = GetHostName();
            
            PortalPage page = PortalContext.Current.PortalPage;

            if (true) //(page.Type == "portlet")
            {
                ColumnInfo[] columns = page.Columns;
                if (columns != null)
                {
                    for (int i = 0; i < columns.Length; i++)
                    {
                        ColumnInfo col = columns[i];

                        Control cc = control.FindControl(col.Name);
                        if (cc == null)
                            continue;

                        foreach (int instId in col.Instances)
                        {
                            PortletInstance p1 = portalService.LoadPortlet(instId);
                            if (p1 != null)
                            {
                                PortletView view = new PortletView(p1);
                                cc.Controls.Add(view);
                            }
                            else
                            {
                                ExceptionControl mc = new ExceptionControl(instId, new Exception("portlet not found."));
                                cc.Controls.Add(mc);
                            }
                        }
                    }
                }
            }
        }

        protected override Control LoadSkin()
        {
            Control control = Page.LoadControl(PortalContext.Current.Layout.Control);
            return control;
        }

        private string GetHostName()
        {
            string hostName;

            if (Page.Request.Url.Port == 80)
                hostName = "http://" + Page.Request.Url.Host;
            else
                hostName = "http://" + Page.Request.Url.Host + ":" + Page.Request.Url.Port;

            return hostName;
        }
    }
}
